package layers;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Random;

public class LayerOneClient {
	
	DatagramSocket clientSocket;
	InetAddress IPAddress;
	DatagramPacket sendPacket;
	DatagramPacket receivePacket;
	
	//Constructor
	public LayerOneClient() throws SocketException, UnknownHostException{
		clientSocket = new DatagramSocket();
		IPAddress = InetAddress.getByName("localhost");
	}
	
	public void clientSend(String sentence) throws Exception{
		byte[] sendData = new byte[sentence.length()];
		sendData = sentence.getBytes();
		sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
		//Poniendo algo de ruido y probabilidad de enviar doble.
		if (noise() == false){
			clientSocket.send(sendPacket);
			if (duplicated() == true)
				clientSocket.send(sendPacket);
				
		}
	}
	
	public String clientReceived() throws IOException{
		byte[] receiveData = new byte[1024];
		receivePacket = new DatagramPacket(receiveData, receiveData.length);
		clientSocket.receive(receivePacket);
		String ack = new String(receivePacket.getData());
		return ack;
	}
	
	
	private boolean duplicated(){
		
		Random prob = new Random();
		boolean dupli = false;
		int num;
		
		num = prob.nextInt(10);

		if(num == 0){
			dupli = true;
		}
		return dupli;
	}
	
	private boolean noise(){
		Random prob = new Random();
		boolean noise=false;
		int num = prob.nextInt(5);

		if(num == 2){
			noise = true;
		}
		return noise;
	}

}
